package cn.bdqn.Bean.dao.impl;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class BaseDao {
    Connection conn = null;

    public Connection getConn() {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/members");
            conn = ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int executeUpdate(String preparedSql, Object[] pm) {
        PreparedStatement pstmt = null;
        int num = 0;
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(preparedSql);
            if (pm != null) {
                for (int i = 0; i < pm.length; i++) {
                    pstmt.setObject(i + 1, pm[i]);
                }
            }
            num = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, pstmt, null);
        }
        return num;
    }
}